﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using Web.App_Code;
using QXBook.Utils;
using QXBook.Service;
using QXBook.Model;

namespace Web
{
    public partial class Login : UserBasePage
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            Title = "用户登录";
            if (!IsPostBack)
            {
                if (HttpContext.Current.Items["Message"] != null && string.IsNullOrEmpty(HttpContext.Current.Items["Message"].ToString()))
                {
                    litAlert.Text = HttpContext.Current.Items["Message"].ToString();
                }
            }

            if (this.userInfo != null)
            {
                phNoLogin.Visible = false;
                phIsLogin.Visible = true;
            }
            else
            {
                phNoLogin.Visible = true;
                phIsLogin.Visible = false;
            }
            btnSave.Click += new EventHandler(btnSave_Click);
            btnReg.Click += new EventHandler(btnReg_Click);
        }

        void btnSave_Click(object sender, EventArgs e)
        {
            LoginMethod();
        }

        void btnReg_Click(object sender, EventArgs e)
        {
            Response.Redirect("Register.aspx");
        }

        /// <summary>
        /// 用户登陆
        /// </summary>
        private void LoginMethod()
        {
            string adminname = CommonUtils.Post("iUserName");
            string password = CommonUtils.Post("iPassWord");

            if (string.IsNullOrEmpty(adminname) || string.IsNullOrEmpty(password))
            {
                ResponseErch("请输入用户名和密码");
                return;
            }

            string rtn = string.Empty;
            try
            {
                rtn = ServiceFactory.CreateInstance<UsersService>().UserLogin(adminname, CommonUtils.MD5(password));

            }
            catch (Exception ex)
            {
                ResponseErch(ex.Message.ToString());
                return;
            }

            if (rtn != MsgConst.OK)
            {
                ResponseErch(rtn);
            }
            else
            {
                if (!string.IsNullOrEmpty(CommonUtils.Get("returnurl")))
                {
                    Response.Redirect(CommonUtils.Get("returnurl"));
                }
                else
                {
                    Response.Redirect("Default.aspx");
                }
            }
        }
    }
}